<?php

namespace App\Models;

use App\Common\Constant\Params;
use App\Services\IStorageService;
use Illuminate\Database\Eloquent\Model;

class OrderGoods extends BaseModel
{

    protected $table = 'orders_goods';

    const CREATED_AT = 'add_time';
    const UPDATED_AT = 'upd_time';

    protected $dateFormat = 'U';

    protected $fillable = [
        'order_id',
        'goods_id',
        'goods_type',
        'goods_name',
        'goods_mark',
        'goods_num',
        'goods_img',
        'goods_price',
    ];

    protected $appends = ['goods_img_url'];

    protected $touches = ['order'];

    public function order(){
        return $this->belongsTo(Order::class,'order_id');
    }

    public function setGoodsImgAttribute($value)
    {
        $this->attributes['goods_img'] = implode(',',(array)$value);
    }

    public function getGoodsImgAttribute($value)
    {
        return $value ? explode(',',$value) : [];
    }

    /**
     * 获取货品封面图url绝对地址
     * @param  string  $value
     * @return string
     */
    public function getGoodsImgUrlAttribute()
    {
        if (empty($this->goods_img)){
            return;
        }
        return resolve(IStorageService::class)->getUrl($this->goods_img[0]);
    }

    /**
     * 获取货品类别文本
     */
    public function getGoodsTypeTextAttribute()
    {
        return Params::$GOODS_CATEGORY[$this->goods_type];
    }

}
